﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input.Touch;
using System.Threading;
using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;



namespace GameForKids
{

    public class GamePlayMemory : DrawableGameComponent
    {
        // bien dem thoi gian
        public float milisecon = 0;
        // hien thi thoi gian choi
        public string timePlay = "";

        // tao 2 mang cell doi xung nhau
        private List<Cell> cellsA;
        private List<Cell> cellsB;
        //
        private Cell cella;
        private Cell cellb;
        private string[] alphabet;
        private List<string> listAlphaBet;

        // mang vi tri tat ca cac cell
        private List<Point> points;


        //kich thuoc cell o moi level
        private int sizeOfCell;

        // toa do x cua cell dau tien
        private int firstPoint;

        // so cell trong mot man
        private int cellOfLevel;

        //xet so o da lat
        private int numCellUp = 0;

        //mang chua gia tri 2 o da lat
        private List<int> twocell;

        private SpriteFont font;

        // hieu ung ngoi sao
        Animation startAnimation;
        Animation startAnimation2;

        // am thanh trong game
        private SoundEffect inCorrect;
        private SoundEffect _correct;
        private SoundEffect correct;

        // kiem tra am thanh chi phat 1 lan
        private bool playOneTime = true;

        // kiem tra 2 o da lat giong nhau
        private bool twoCellTrue = false;

        // trang thai cua game
        private enum GameStateMini
        {
            playing,
            checking,
            win,
        }

        public bool iswin = false;
        SpriteFont helpfont;
        //luu diem 1 lan, tranh lap lai
        private GameStateMini gamestatemini;
        public int moved = 0;
        // tao co so du lieu
        private string strConnectionString = @"isostore:/LowerCaseMemoryDB.sdf";

        // cong thuc tinh diem

        public static string CongThucGoc = "(12*L*10)/N+3";
        public static string CongThucHienTai = "";


        public GamePlayMemory(Game game) : base(game)
        {

            helpfont = this.Game.Content.Load<SpriteFont>("Fonts/HelpFont");

            listAlphaBet = new List<string>();
            cellsA = new List<Cell>();
            cellsB = new List<Cell>();

            switch (GameForKids.gameState)
            {
                case GameState.Memory:
                    {
                        font = this.Game.Content.Load<SpriteFont>("Fonts/ChartFont");
                        strConnectionString = @"isostore:/MemoryDB.sdf";
                        for(int i=1; i<=20;i++)
                        {
                            cella = new Cell(game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/pic" + i.ToString()), "", font);
                            cellsA.Add(cella);
                            cellb = new Cell(game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/pic" + i.ToString()), "", font);
                            cellsB.Add(cellb);
                        }
                    }
                    break;
                case GameState.AlphabetMemory:
                    {
                        font = this.Game.Content.Load<SpriteFont>("Fonts/ChartFont");
                        strConnectionString = @"isostore:/UpperCaseMemoryDB.sdf";
                        if(GameForKids.language == GameForKids.VIET)
                             alphabet = new string[] {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
                                 "Q","R","S","T","U","V","W","X","Y","Z","Ô","Ơ","Ư","Ê","Ă","Â"};
                        else
                            alphabet = new string[] {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
                                  "Q","R","S","T","U","V","W","X","Y","Z"};
                        foreach (string c in alphabet)
                        {
                            cella = new Cell(game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoMo"), c, font);
                            cellsA.Add(cella);
                            cellb = new Cell(game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoMo"), c, font);
                            cellsB.Add(cellb);
                        }
                    }
                    break;
                case GameState.NumbersMemory:
                    {
                        font = this.Game.Content.Load<SpriteFont>("Fonts/ChartFont");
                        strConnectionString = @"isostore:/NumbersMemoryDB.sdf";
                        alphabet = new string[100];
                        for (int i = 0; i < 100; i++)
                        {
                            alphabet[i] = i.ToString();
                        }
                        foreach (string c in alphabet)
                        {
                            cella = new Cell(game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoMo"), c, font);
                            cellsA.Add(cella);
                            cellb = new Cell(game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoMo"), c, font);
                            cellsB.Add(cellb);
                        }
                    }
                    break;
                case GameState.SoundMemory:
                    {
                        font = this.Game.Content.Load<SpriteFont>("Fonts/ChartFont");
                        strConnectionString = @"isostore:/SoundMemoryDB.sdf";
                        alphabet = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
                            "13", "14", "15", "16", "17", "18", "19", "20" };
                        foreach (string c in alphabet)
                        {
                            cella = new Cell(game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/speaker"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/speaker_press"), c, font);
                            cellsA.Add(cella);
                            cellb = new Cell(game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/speaker"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/speaker_press"), c, font);
                            cellsB.Add(cellb);
                        }
                    }
                    break;
            }


            points = new List<Point>();
            twocell = new List<int>();
            twocell.Add(-1);
            twocell.Add(-1);


            gamestatemini = GameStateMini.playing;

            // doc thong so cua hieu ung ngoi sao tu file xml
            XDocument doc = XDocument.Load("Content/XML/StartAnimationDef.xml");
            XName name = XName.Get("Definition");
            var definitions = doc.Document.Descendants(name);
            foreach (var animationDefinition in definitions)
            {
                string animationAlias = animationDefinition.Attribute("Alias").Value;
                Texture2D texture = this.Game.Content.Load<Texture2D>(animationDefinition.Attribute("SheetName").Value);
                Point frameSize = new Point();
                frameSize.X = int.Parse(animationDefinition.Attribute("FrameWidth").Value);
                frameSize.Y = int.Parse(animationDefinition.Attribute("FrameHeight").Value);
                Point sheetSize = new Point();
                sheetSize.X = int.Parse(animationDefinition.Attribute("SheetColumns").Value);
                sheetSize.Y = int.Parse(animationDefinition.Attribute("SheetRows").Value);
                TimeSpan frameInterval = TimeSpan.FromSeconds((float)1 / int.Parse(animationDefinition.Attribute("Speed").Value));
                startAnimation = new Animation(texture, frameSize, sheetSize);
                startAnimation.PlayFromFrameIndex(0);
                startAnimation.Active();
                startAnimation2 = new Animation(texture, frameSize, sheetSize);
                startAnimation2.PlayFromFrameIndex(0);
                startAnimation2.Active();
            }

            inCorrect = this.Game.Content.Load<SoundEffect>("MemoryGame/Sounds/inCorrect");
            correct = this.Game.Content.Load<SoundEffect>("MemoryGame/Sounds/correct");
            _correct = this.Game.Content.Load<SoundEffect>("MemoryGame/Sounds/_correct");

            // tao csdl
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                if (readAndWriteDB.DatabaseExists() == false)
                {
                    readAndWriteDB.CreateDatabase();
                }
            }


            // lay cong thuc
            using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isolatedStorageFile.FileExists("CongThuc"+GameForKids.gameState.ToString()+".txt"))
                {
                    using (IsolatedStorageFileStream isfs = isolatedStorageFile.OpenFile("CongThuc" + GameForKids.gameState.ToString() + ".txt", FileMode.Open))
                    {
                        using (StreamReader reader = new StreamReader(isfs))
                        {
                            while (!reader.EndOfStream)
                            {
                                CongThucHienTai = reader.ReadLine();
                            }
                        }
                    }
                }
            }
            if (CongThucHienTai == "" || CongThucHienTai == null)
                CongThucHienTai = CongThucGoc;

        }


        // giai phong bo nho
        public void unload()
        {
            cellsA = null;
            cellsB = null;
            listAlphaBet = null;
            alphabet = null;
            points = null;
            twocell = null;
        }

        // random chart
        private void randomChar()
        {
            listAlphaBet.Clear();
            cellsA.Clear();
            cellsB.Clear();
            int temp;
            Random rand = new Random();
            switch (GameForKids.gameState)
            {
                case GameState.Memory:
                    {
                        for (int i = 1; i <= 20; i++)
                        {
                            listAlphaBet.Add("pic" + i.ToString());
                        }
                            while (listAlphaBet.Count > 0)
                            {
                                temp = rand.Next(0, listAlphaBet.Count);
                                cella = new Cell(this.Game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                    this.Game.Content.Load<Texture2D>("MemoryGame/Images/" + listAlphaBet[temp]), "", font);
                                cellsA.Add(cella);
                                cellb = new Cell(this.Game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                    this.Game.Content.Load<Texture2D>("MemoryGame/Images/" + listAlphaBet[temp]), "", font);
                                cellsB.Add(cellb);
                                listAlphaBet.RemoveAt(temp);
                            }
                    }
                    break;
                case GameState.SoundMemory:
                    {
                        foreach (string c in alphabet)
                        {
                            listAlphaBet.Add(c);
                        }

                        while (listAlphaBet.Count > 0)
                        {
                            temp = rand.Next(0, listAlphaBet.Count);

                            cella = new Cell(this.Game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/speaker"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/speaker_press"), listAlphaBet[temp], font);
                            cellsA.Add(cella);

                            cellb = new Cell(this.Game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/speaker"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/speaker_press"), listAlphaBet[temp], font);
                            cellsB.Add(cellb);
                            listAlphaBet.RemoveAt(temp);
                        }
                    }
                    break;
                default:
                    {
                        foreach (string c in alphabet)
                        {
                            listAlphaBet.Add(c);
                        }

                        while (listAlphaBet.Count > 0)
                        {
                            temp = rand.Next(0, listAlphaBet.Count);
                            cella = new Cell(this.Game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoMo"), listAlphaBet[temp], font);
                            cellsA.Add(cella);
                            cellb = new Cell(this.Game, this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoUp"),
                                this.Game.Content.Load<Texture2D>("MemoryGame/Images/SaoMo"), listAlphaBet[temp], font);
                            cellsB.Add(cellb);
                            listAlphaBet.RemoveAt(temp);
                        }
                    }
                    break;
            }
        }
        // luu theo dang ID - ten  - level - diem - ngay
        public void saveScore(int diem)
        {
            string _name = GameForKids.userName;
            int _level = MemoryGame.level;
            int _score = diem;
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                DataScore newscore = new DataScore { ID = DateTime.Now.ToString(),
                                                     name = _name, 
                                                     level = _level,
                                                     score = _score,
                                                     day = DateTime.Today.ToShortDateString() };
                readAndWriteDB.TableScore.InsertOnSubmit(newscore);
                readAndWriteDB.SubmitChanges();
            }
        }
        private IList<DataScore> getListDataScore(string _name, int _level)
        {
            IList<DataScore> listDataScore = null;
            using (ReadAndWrite readAndWrite = new ReadAndWrite(strConnectionString))
            {
                IQueryable<DataScore> dataScoreQuery = from data in readAndWrite.TableScore where data.name.Equals(_name) && data.level == _level select data;
                listDataScore = dataScoreQuery.ToList();
            }
            return listDataScore;
        }

        public void startNewLevel(int _level)
        {
            iswin = false;
            ChartScreen.listDataScore = this.getListDataScore(GameForKids.userName, MemoryGame.level);
            // cho tat ca cac cell lat up lai khi qua man moi
            foreach (Cell cell in cellsA)
            {
                cell.hardReset();
                cell.Enable();
            }

            foreach (Cell cell in cellsB)
            {
                cell.hardReset();
                cell.Enable();
            }
            // xoa mang vi tri
            points.Clear();
            int temp;
            Random rand = new Random();
            randomChar();
            moved = 0;
            milisecon = 0;
            numCellUp = 0;
            twocell[0] = -1;
            twocell[1] = -1;
            switch (MemoryGame.level)
            {
                case 1:
                    {
                        cellOfLevel = 12;
                        firstPoint = 114;
                        sizeOfCell = 143;
                        // tao moi mot mang vi tri moi
                        for (int r = 0; r < 3; r++)
                            for (int c = 0; c < 4; c++)
                            {
                                Point point = new Point(firstPoint + sizeOfCell * c, 20 + r * sizeOfCell);
                                points.Add(point);
                            }
                        // lay random tu mang point set cho 2 mang Cell
                        while (cellOfLevel > 0)
                        {
                            temp = rand.Next(0, cellOfLevel);
                            if (cellOfLevel > 6)

                                cellsA[cellOfLevel - 7].Location = points[temp];

                            else
                                cellsB[cellOfLevel - 1].Location = points[temp];
                            points.RemoveAt(temp);
                            cellOfLevel--;
                        }
                        cellOfLevel = 12;
                    }; break;
                case 2:
                    {
                        cellOfLevel = 20;
                        firstPoint = 132;
                        sizeOfCell = 107;
                        // tao moi mot mang vi tri moi
                        for (int r = 0; r < 4; r++)
                            for (int c = 0; c < 5; c++)
                            {
                                Point point = new Point(firstPoint + sizeOfCell * c, 20 + r * sizeOfCell);
                                points.Add(point);
                            }
                        // lay random tu mang point set cho 2 mang Cell
                        while (cellOfLevel > 0)
                        {
                            temp = rand.Next(0, cellOfLevel);
                            if (cellOfLevel > 10)

                                cellsA[cellOfLevel - 11].Location = points[temp];

                            else
                                cellsB[cellOfLevel - 1].Location = points[temp];
                            points.RemoveAt(temp);
                            cellOfLevel--;
                        }
                        cellOfLevel = 20;
                    }; break;
                case 3:
                    {
                        cellOfLevel = 24;
                        firstPoint = 100;
                        sizeOfCell = 100;
                        // tao moi mot mang vi tri moi
                        for (int r = 0; r < 4; r++)
                            for (int c = 0; c < 6; c++)
                            {
                                Point point = new Point(firstPoint + sizeOfCell * c, 20 + r * sizeOfCell);
                                points.Add(point);
                            }
                        // lay random tu mang point set cho 2 mang Cell
                        while (cellOfLevel > 0)
                        {
                            temp = rand.Next(0, cellOfLevel);
                            if (cellOfLevel > 12)

                                cellsA[cellOfLevel - 13].Location = points[temp];

                            else
                                cellsB[cellOfLevel - 1].Location = points[temp];
                            points.RemoveAt(temp);
                            cellOfLevel--;
                        }
                        cellOfLevel = 24;
                    }; break;
                case 4:
                    {
                        cellOfLevel = 30;
                        firstPoint = 142;
                        sizeOfCell = 86;
                        // tao moi mot mang vi tri moi
                        for (int r = 0; r < 5; r++)
                            for (int c = 0; c < 6; c++)
                            {
                                Point point = new Point(firstPoint + sizeOfCell * c, 20 + r * sizeOfCell);
                                points.Add(point);
                            }
                        // lay random tu mang point set cho 2 mang Cell
                        while (cellOfLevel > 0)
                        {
                            temp = rand.Next(0, cellOfLevel);
                            if (cellOfLevel > 15)

                                cellsA[cellOfLevel - 16].Location = points[temp];

                            else
                                cellsB[cellOfLevel - 1].Location = points[temp];
                            points.RemoveAt(temp);
                            cellOfLevel--;
                        }
                        cellOfLevel = 30;
                    }; break;
                case 5:
                    {
                        cellOfLevel = 40;
                        firstPoint = 100;
                        sizeOfCell = 75;
                        // tao moi mot mang vi tri moi
                        for (int r = 0; r < 5; r++)
                            for (int c = 0; c < 8; c++)
                            {
                                Point point = new Point(firstPoint + sizeOfCell * c, 20 + r * sizeOfCell);
                                points.Add(point);
                            }
                        // lay random tu mang point set cho 2 mang Cell
                        while (cellOfLevel > 0)
                        {
                            temp = rand.Next(0, cellOfLevel);
                            if (cellOfLevel > 20)

                                cellsA[cellOfLevel - 21].Location = points[temp];

                            else
                                cellsB[cellOfLevel - 1].Location = points[temp];
                            points.RemoveAt(temp);
                            cellOfLevel--;
                        }
                        cellOfLevel = 40;
                    }; break;
            }
        }
        //tinh diem
        public int getScore()
        {
            int mark = 0;
            XuLyCongThuc xulycongthuc;
            string s = "";

                xulycongthuc = new XuLyCongThuc();
                s = xulycongthuc.TinhDiem(CongThucHienTai, moved, (int)(milisecon / 1000), MemoryGame.level);
                double d = double.Parse(s);
            mark = (int)d;

            if (mark >= 10)
                return 10;
            if (mark <= 0)
                mark = 0;
            return mark;
        }

        // neu tat ca cac cell deu a^n thi Win
        public void checkWin(float elapsed)
        {
            switch (MemoryGame.level)
            {
                case 1:
                    {
                        for (int i = 0; i < 6; i++)
                        {
                            if (cellsA[i].Enabled || cellsB[i].Enabled) return;
                        }
                    }; break;
                case 2:
                    {
                        for (int i = 0; i < 10; i++)
                        {
                            if (cellsA[i].Enabled || cellsB[i].Enabled) return;
                        }
                    }; break;
                case 3:
                    {
                        for (int i = 0; i < 12; i++)
                        {
                            if (cellsA[i].Enabled || cellsB[i].Enabled) return ;
                        }
                    }; break;
                case 4:
                    {
                        for (int i = 0; i < 15; i++)
                        {
                            if (cellsA[i].Enabled || cellsB[i].Enabled) return;
                        }
                    }; break;
                case 5:
                    {
                        for (int i = 0; i < 20; i++)
                        {
                            if (cellsA[i].Enabled || cellsB[i].Enabled) return;
                        }
                    }; break;
            }

            timeDelay += elapsed;
            if (timeDelay >= 500)
            {
                iswin = true;
                timeDelay = 0;
            }
        }
        float timeDelay=0;

        private void checkTwoCell(float elapsed)
        {
            // truong hop 2 hinh bang nhau
            if (twocell[0] == (twocell[1] - 20))
            {
                // phat am thanh
                if (GameForKids.ISMUSIC && playOneTime && GameForKids.gameState!=GameState.SoundMemory)
                {
                    _correct.Play();
                    playOneTime = false;
                }

                timeDelay += elapsed;
                if (timeDelay >= 500)
                    twoCellTrue = true;
                // hien 1s truoc khi mat
                if (timeDelay >= 1000)
                {
                    cellsA[twocell[0]].pressed = false;
                    cellsA[twocell[0]].Disable();
                    cellsB[twocell[1] - 20].pressed = false;
                    cellsB[twocell[1] - 20].Disable();
                    numCellUp = 0;
                    twocell[0] = -1;
                    twocell[1] = -1;

                    twoCellTrue = false;
                    startAnimation.PlayFromFrameIndex(0);
                    startAnimation2.PlayFromFrameIndex(0);
                    timeDelay = 0;
                    gamestatemini = GameStateMini.playing;
                    playOneTime = true;
                    if (GameForKids.ISMUSIC && playOneTime && GameForKids.gameState!=GameState.SoundMemory)
                    {
                        correct.Play();
                    }
                }
            }
            else
            {

                if (GameForKids.ISMUSIC && playOneTime && GameForKids.gameState != GameState.SoundMemory)
                {
                    inCorrect.Play();
                    playOneTime = false;
                }
                // 2 hinh deu thuoc mang A
                if (twocell[0] < 20 && twocell[1] < 20)
                {
                    timeDelay += elapsed;
                    cellsA[twocell[0]].Effect(timeDelay);
                    cellsA[twocell[1]].Effect(timeDelay);
                    if (timeDelay >= 1000)
                    {
                        cellsA[twocell[0]].reset();
                        cellsA[twocell[1]].reset();
                        numCellUp = 0;
                        twocell[0] = -1;
                        twocell[1] = -1;

                        timeDelay = 0;
                        gamestatemini = GameStateMini.playing;
                        playOneTime = true;
                    }
                }
                // 2 hinh deu thuoc mang B
                if (twocell[0] >= 20 && twocell[1] >= 20)
                {
                    timeDelay += elapsed;
                    cellsB[twocell[0] - 20].Effect(timeDelay);
                    cellsB[twocell[1] - 20].Effect(timeDelay);

                    if (timeDelay >= 1000)
                    {
                        cellsB[twocell[0] - 20].reset();
                        cellsB[twocell[1] - 20].reset();
                        numCellUp = 0;
                        twocell[0] = -1;
                        twocell[1] = -1;

                        timeDelay = 0;
                        gamestatemini = GameStateMini.playing;
                        playOneTime = true;
                    }

                }
                // 2 hinh thuoc 2 mang khac nhau nhung khac ID
                if (twocell[0] < 20 && twocell[1] >= 20)
                {

                    timeDelay += elapsed;
                    cellsA[twocell[0]].Effect(timeDelay);
                    cellsB[twocell[1] - 20].Effect(timeDelay);

                    if (timeDelay >= 1000)
                    {
                        cellsA[twocell[0]].reset();
                        cellsB[twocell[1] - 20].reset();
                        numCellUp = 0;
                        twocell[0] = -1;
                        twocell[1] = -1;

                        timeDelay = 0;
                        gamestatemini = GameStateMini.playing;
                        playOneTime = true;
                    }
                }

            }

        }

        public override void Initialize()
        {
            base.Initialize();
        }

        //toc do cua animation cac ngoi sao
        private float frameTime = 0f;

        public override void Update(GameTime gameTime)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds;
            // bat dau choi thi tinh gio
            if (MemoryGame.viewState == MemoryGame.ViewState.Playing)
            {
                milisecon += elapsed;
                setTimePlay();
            }
            // neu 2 o da lat thi check
            if (numCellUp >= 2)
            {
                gamestatemini = GameStateMini.checking;
                checkTwoCell(elapsed);
            }
            checkWin(elapsed);
            frameTime += elapsed;
            if (frameTime >= 60)
            {
                startAnimation.Update();
                startAnimation2.Update();
                frameTime = 0f;
            }

            base.Update(gameTime);
        }

        public void setTimePlay()
        {
            timePlay = ((int)milisecon / 60000).ToString() + " : " + (((int)milisecon / 1000) % 60).ToString();
        }

        public virtual void Draw(GameTime gametime, SpriteBatch spriteBatch)
        {

            // tuy theo  level ma ve so cellA voi cellB thich hop
            switch (MemoryGame.level)
            {
                case 1:
                    {
                        for (int i = 0; i < 6; i++)
                        {
                            cellsA[i].Draw(spriteBatch, sizeOfCell);
                            cellsB[i].Draw(spriteBatch, sizeOfCell);
                        }
                    }; break;
                case 2:
                    {
                        for (int i = 0; i < 10; i++)
                        {
                            cellsA[i].Draw(spriteBatch, sizeOfCell);
                            cellsB[i].Draw(spriteBatch, sizeOfCell);
                        }
                    }; break;
                case 3:
                    {
                        for (int i = 0; i < 12; i++)
                        {
                            cellsA[i].Draw(spriteBatch, sizeOfCell);
                            cellsB[i].Draw(spriteBatch, sizeOfCell);
                        }
                    }; break;
                case 4:
                    {
                        for (int i = 0; i < 15; i++)
                        {
                            cellsA[i].Draw(spriteBatch, sizeOfCell);
                            cellsB[i].Draw(spriteBatch, sizeOfCell);
                        }
                    }; break;
                case 5:
                    {
                        for (int i = 0; i < 20; i++)
                        {
                            cellsA[i].Draw(spriteBatch, sizeOfCell);
                            cellsB[i].Draw(spriteBatch, sizeOfCell);
                        }
                    }; break;
            }

            //hai o dung hien 0,5s sau do hieu ung sao xet va mat
            if (twoCellTrue)
            {
                startAnimation.Draw(spriteBatch,
                    new Vector2(cellsA[twocell[0]].Location.X - ((200 - sizeOfCell) / 2),
                                       cellsA[twocell[0]].Location.Y - ((200 - sizeOfCell) / 2)),
                                       SpriteEffects.None, 1.0f,255);
                startAnimation2.Draw(spriteBatch,
                       new Vector2(cellsB[twocell[1] - 20].Location.X - ((200 - sizeOfCell) / 2),
                                          cellsB[twocell[1] - 20].Location.Y - ((200 - sizeOfCell) / 2)),
                                           SpriteEffects.None, 1.0f,255);
            }
           

                spriteBatch.DrawString(helpfont, timePlay, new Vector2(10, 250), Color.White);
                spriteBatch.DrawString(helpfont, moved.ToString(), new Vector2(740, 250), Color.White);
        
        }

        public void TouchEvent(TouchLocation touch)
        {
            // truong hop dan check 2 cell thi khong duoc lam gi ca
            if (gamestatemini == GameStateMini.playing)
            {

                foreach (Cell cell in cellsA)
                {
                    cell.TouchEvent(touch);
                    // neu co cell da lat thi add vi tri no vao twoCell
                    if (cell.pressed)
                    {
                        if (twocell[0] < 0)
                        {
                            twocell[0] = cellsA.IndexOf(cell);
                            numCellUp++;
                            moved++;
                        }
                        if (twocell[0] > -1 && twocell[0] != cellsA.IndexOf(cell))
                        {
                            twocell[1] = cellsA.IndexOf(cell);
                            numCellUp++;
                            moved++;
                        }
                    }
                    else
                    {
                        // neu cell da lat sau do up thi xoa vi tri trong twoCell
                        if (twocell[0] > -1 && twocell[0] == cellsA.IndexOf(cell))
                        {
                            twocell[0] = -1;
                            numCellUp--;
                            moved++;
                        }
                    }
                }

                //xu ly touch event doi voi moi cell va luu vi tri neu no lat
                foreach (Cell cell in cellsB)
                {
                    cell.TouchEvent(touch);
                    if (cell.pressed)
                    {
                        if (twocell[1] < 0)
                        {
                            twocell[1] = cellsB.IndexOf(cell) + 20;
                            numCellUp++;
                            moved++;
                        }
                        if (twocell[1] > -1 && twocell[1] != cellsB.IndexOf(cell) + 20)
                        {
                            twocell[0] = cellsB.IndexOf(cell) + 20;
                            numCellUp++;
                            moved++;
                        }
                    }
                    else
                    {
                        if (twocell[1] > -1 && twocell[1] == (cellsB.IndexOf(cell) + 20))
                        {
                            twocell[1] = -1;
                            numCellUp--;
                            moved++;
                        }
                    }
                }
            }
        }




    }
}
